package com.example.netty.handler;

import com.alibaba.fastjson.JSON;
import com.example.netty.common.Message;
import com.example.netty.constant.ReqMessageType;
import com.example.netty.service.RoomService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author zclever <304078606@qq.com>
 * @date 2021-03-03
 */
@Component
@ChannelHandler.Sharable
public class RoomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(RoomHandler.class);

    @Autowired
    private RoomService roomService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        Message req = JSON.parseObject(msg.text(), Message.class);
        if(req.getType()== ReqMessageType.inRoom){
            logger.info("用户进入房间:{}", req.getContent());

            Message res = roomService.inRoom(ctx.channel(),req.getContent());
            ctx.channel().writeAndFlush(res.toMsg());
        }else if(req.getType()== ReqMessageType.outRoom){
            logger.info("用户退出房间:{}", req.getContent());

            Message res = roomService.outRoom(ctx.channel(),req.getContent());
            ctx.channel().writeAndFlush(res.toMsg());
        }else{
            msg.retain();
            ctx.fireChannelRead(msg);
        }
    }

}
